package spring.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import spring.domain.UserLog;
import spring.service.UserService;
import spring.test.HttpContextUtil;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

@Aspect
@Component
public class LogAopAspect {

    @Pointcut("execution(public * spring.controller.UserController.allLogs(..))")
    public void logPointCut() {
        System.out.println("切入点");
    }
    @Before("logPointCut()")
    public void doBefore(){
        System.out.println("=====前置通知开始=====");
    }

    @After("logPointCut()")
    public void saveOperation(JoinPoint joinPoint) {
        UserLog userLog = new UserLog();
        System.out.println("save");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = HttpContextUtil.getIpAddress();
        userLog.setIp(ip);
        String name = (String) request.getSession().getAttribute("name");
        userLog.setName(name);
        userLog.setTime(new Date());
        (new UserService()).insert(userLog);
    }
}
